<?php

namespace app\traits;

use think\exception\HttpResponseException;

/**
 * api数据返回格式
 * Trait ResponseTrait
 * @package app\traits
 */
trait ResponseTrait
{

    /**
     * 请求成功响应
     * @param array $data
     * @param int $httpStatus
     */
    protected function success($data = [], $message = "", int $httpStatus = 200)
    {
        $response = [
            "code" => $code = 0,
            "message" => $message,
            "data" => $data,
        ];
        throw new HttpResponseException(json($response, $httpStatus));
    }

    /**
     * 失败请求响应
     * @param $code
     * @param string $message
     * @param int $httpStatus
     */
    protected function error($code, $message, int $httpStatus = 200)
    {
        $response = [
            "code" => $code,
            "message" => $message,
            "data" => $data = [],
        ];

        throw new HttpResponseException(json($response, 200));//  请求固定返回 200
    }
}